package com.tfswx.fljdmxyy.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanCopier;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 对象属性值复制
 *
 * @author: 陈文佳
 * @date: 2021/4/15
 **/
@Slf4j
public class ConverterUtils {
    private ConverterUtils() {
    }

    public static <S, T> void convert(S source, T target) {
        if (source == null) {
            return;
        }
        BeanCopier copier = BeanCopier.create(source.getClass(), target.getClass(), false);
        copier.copy(source, target, null);
    }

    public static <S, T> List<T> convertList(List<S> sourceList, Class<T> targetClazz) {
        if (sourceList == null) {
            return Collections.emptyList();
        }
        List<T> targetList = new ArrayList<>();
        for (S source : sourceList) {
            T target = convert(source, targetClazz);
            targetList.add(target);
        }
        return targetList;
    }

    public static <S, T> T convert(S source, Class<T> target) {
        if (source == null) {
            return null;
        }
        BeanCopier copier = BeanCopier.create(source.getClass(), target, false);
        T instance = null;
        try {
            instance = target.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            log.error(String.valueOf(e.getStackTrace()));
        }
        copier.copy(source, instance, null);
        return instance;
    }


    public static <T> T setAttributeNull(T t) throws IllegalAccessException {
        Field[] declaredFields = t.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            Object o = field.get(t);
            if (o != null && "null".equalsIgnoreCase(o.toString())) {
                field.set(t, null);
            }
        }
        return t;
    }

}
